package com.coolingme.springcloud.sentinel;

import com.alibaba.csp.sentinel.cluster.ClusterStateManager;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyue
 * @date 2022/10/18 11:35
 */
@SpringBootApplication
public class SpringCloudSentinelExampleApplication {

    public static void main(String[] args) {
        // 初始化限流规则，单个应用
//        initFlowRule();

        // 集群配置：设置当前服务为客户端
        ClusterStateManager.applyState(ClusterStateManager.CLUSTER_CLIENT);

        SpringApplication.run(SpringCloudSentinelExampleApplication.class, args);
    }


    /**
     * 初始化限流规则
     *
     * @author wangyue
     * @date 2022/10/18 10:34
     */
    private static void initFlowRule() {
        List<FlowRule> flowRuleList = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        // 设置资源，@SentinelResource(value = "say")配置的值
        flowRule.setResource("say");
        // 限流阈值的类型 QPS（每秒查询率）
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 限制并发数
//        flowRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        // 设置QPS为5
        flowRule.setCount(5);
        // 控制行为策略
        flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        // 调用关系限流
        flowRule.setStrategy(RuleConstant.STRATEGY_RELATE);
        // 设置关联的资源
        flowRule.setRefResource("write");

        flowRuleList.add(flowRule);
        // 加载限流规则，对同一个资源设置多个限流规则，进行遍历
        FlowRuleManager.loadRules(flowRuleList);
    }

}
